package com.lovo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.dao.MovieDao;
import com.lovo.dao.OrderDao;
import com.lovo.entity.MovieEntity;
import com.lovo.entity.OrderEntity;
import com.lovo.service.RemoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class MovieController {
    @Autowired
    MovieDao movieDao;
    @Autowired
    OrderDao orderDao;
    @Autowired
    RemoteService remoteService;

    /***
     * 被远程调用的接口，提供电影票，当月
     */
    @GetMapping("currentMonthMovie/{date}")
    public List<MovieEntity> currentMonthMovie(@PathVariable("date") String date) {
        QueryWrapper<MovieEntity> q = new QueryWrapper<>();
        q.eq("movieDate", date);
//        List<MovieEntity> list = movieDao.findAllByMovieDate(date);
        List<MovieEntity> list = movieDao.selectList(q);
        return list;
    }

    @GetMapping("orderEntityList")
    public List<OrderEntity> orderEntityList() {
        List<OrderEntity> list = orderDao.selectList(null);
        for (int i = 0; i < list.size(); i++) {
            OrderEntity e = list.get(i);
            MovieEntity mo = movieDao.selectById(e.getMovieId());
            e.setMovieEntity(mo);
        }
        return list;
    }

    @GetMapping("confirmTicket/{orderNum}/{id}")
    public boolean confirmTicket(@PathVariable("orderNum") String orderNum,
                                 @PathVariable("id") long id) {
        //修改本地
//        OrderEntity orderEntity = orderDao.findById(id).get();
        OrderEntity orderEntity = orderDao.selectById(id);
        int movId = orderEntity.getMovieId();
        MovieEntity m = movieDao.selectById(movId);
        //有票时候情况
        boolean flag;
        if (m.getMovieNum() >= orderEntity.getBuyNum()) {
            orderEntity.setTag(1);
            //更新电影票数量
            m.setMovieNum(m.getMovieNum() - orderEntity.getBuyNum());
            movieDao.updateById(m);
            flag = true;
        } else {
            flag = false;
            orderEntity.setTag(2);
        }
        //更新后台票务情况
        orderDao.updateById(orderEntity);
        //远程调用前台进行同步更新票务状态
        if (flag) {
            //前台购票成功为2
            return remoteService.changeTag(orderNum, 2);
        } else {
            //前台购票失败为3
            return remoteService.changeTag(orderNum, 3);
        }

    }
}
